package com.lin.linchatgpt.utils;

import cn.hutool.core.util.StrUtil;
import com.lin.linchatgpt.entity.User;
import com.lin.linchatgpt.exception.LinException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Date;

/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/4/6 16:55
 * @Description JWT
 */
public class JwtUtil {
    // token时效：24小时
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    // 签名哈希的密钥，对于不同的加密算法来说含义不同
    public static final String APP_SECRET = "LINWX";

    /**
     * 根据用户id和昵称生成token
     *
     * @param userId   用户id
     * @return JWT规则生成的token
     */
    public static String getJwtToken(String userId) {
        return Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("lin-chatGPT")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("userId", userId)
                // HS256算法实际上就是MD5加盐值，此时APP_SECRET就代表盐值
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
    }

    /**
     * 判断token是否存在与有效
     *
     * @param jwtToken token字符串
     * @return 如果token有效返回true，否则返回false
     */
    public static boolean checkToken(String jwtToken) {
        if (StrUtil.isEmpty(jwtToken))
            return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean checkToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("Authorization");
        if (StrUtil.isEmpty(jwtToken))
            return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取会员id
     *
     * @param request Http请求对象
     * @return 解析token后获得的用户id
     */
    public static User getMemberIdByJwtToken(HttpServletRequest request) {
        String Authorization = request.getHeader("Authorization");
        String jwtToken = Authorization.split(" ")[1];
        if (StrUtil.isEmpty(jwtToken))
            throw new LinException(ResultCode.UNAUTHENTICATED, "未登录");
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        User user = new User();
        user.setId((String) claims.get("userId"));
//        user.setUsername((String) claims.get("nickName"));
        return user;
    }

}
